<template>
    <div class="box">
        <div class="item1">
            <!--眉头-->
            <x-button @click.native="clear">清空cookie</x-button>
            <x-button>状态:{{point}}</x-button>
            <x-button>endtime{{end_time}}</x-button>
            <span>{{query}}</span>
            <span>cookie时间{{cookie_time}}</span>
            <span>当前时间{{now_time}}</span>
            <span>datetime:{{downtime}}</span>
            <span>{{user.status}}</span>
            <span>{{sign}}</span>
            <div v-if="userStatus === status.__init">
                <input type="text" v-model="user.userinfo.mch_id">
                <button v-on:click="scan">扫码桌面二维码</button>
                <!--<x-button @click.native="test">测试</x-button>-->
            </div>
            <!--登陆后-->
            <div v-if="userStatus === status.__init">
                等待管理员开启
                <x-button @click.native="refresh">刷新</x-button>
                <x-button @click.native="putin">进入</x-button>
            </div>
            <!--<div v-if="actor.stat === status.__ing">
                本轮正在开奖中,请等待下一轮
            </div>-->
            <!--提示加入-->
            <div v-if="userStatus === status.__ing">
                <div>奖品名称<input type="text" v-model="prize"></div>
                <div>中奖人数<input type="text" v-model="luck_num"></div>
                <div>参与条件<input type="text" v-model="price"></div>
                <!--<div>抽奖时间
                    <input type="text" v-model="luck_time">
                </div>-->
                <x-button type="primary" @click.native="join" plain style="border-radius:99px;width: 94%">参加</x-button>
</div>
<!--加入后-->
<div v-if="userStatus === status.__joined || userStatus === status.__ing" style="margin-left:60px;font-size: 25px">
<clocker :time="downtime" slot="value">
    距离开奖剩余
    <span class="day">%_M1</span>
    <span class="day">%_M2</span>分
    <span class="day">%_S1</span>
    <span class="day">%_S2</span>秒
</clocker>
</div>
<!--<div v-if="actor.stat === status.__ending">等待开奖中</div>
            <div v-if="actor.stat === status.__end">中奖人是
                <div v-for="lucker in actor.luckerArr">{{lucker.nick}}</div>
            </div>-->
</div>
<!--<div class="item2">
            <group>
                <divider>参与记录</divider>
                <div class="box2 body-wrapper">
                    <p v-for="player in actor.userArr">{{ player.nick }}加入了抽奖</p>
                </div>
            </group>
        </div>-->
<!--<div v-transfer-dom >
            <x-dialog style="position:relative;top:-100px;" v-model="show" hide-on-blur :dialog-style="{'max-width': '100%', width: '100%', height: '50%', 'background-color': 'transparent'}">
                <p style="color:#fff;text-align:center;" @click="show = false">
                
                <div style="margin-left:100px">
                <div v-for="lucker in luckerList">
                    昵称:{{lucker.nick}}
                </div>
                
                </div>
                <br>
                <br>
                <x-icon type="ios-close-outline" style="fill:#fff;"></x-icon>
                </p>
            </x-dialog>
        </div>-->
<div v-transfer-dom>
    <x-dialog v-model="show" class="dialog-demo">
        <div style="padding:15px;">
<!--<x-button @click.native="doShowToast" type="primary">show toast</x-button>-->
<div v-for="lucker in luckerArr">
    昵称:{{lucker.nick}}
</div>
</div>
<div @click="show=false">
    <span class="vux-close"></span>
</div>
</x-dialog>
</div>
</div>
</template>

<script>
    import { TransferDomDirective as TransferDom, XDialog, Clocker, XButton, Group, Scroller, Divider } from 'vux'
    import status from '../../api/status.js'
    import actor from '../../api/actor.js'
    import dateformat from 'dateformat'
    // import axios from 'axios'
    import user from '../../api/user.js'
    // import ip from '../../api/ip.js'

    // axios.defaults.baseURL = "http://" + ip
    // axios.defaults.headers['Content-Type']="application/x-www-form-urlencoded"

    export default {
        directives: {
            TransferDom
        },
        components: {
            XDialog,
            Clocker,
            XButton,
            Group,
            Scroller,
            Divider
        },
        data() {
            return {
                trade_no: '',
                query: '',
                point: '',
                cookie_time: '',
                now_time: '',
                status1: 0,
                title: '',
                nick: '',
                downtime: '',
                m: null,
                actor,
                status,
                user,
                userStatus: 0,
                price: 0,
                luck_num: 0,
                prize: '',
                luck_time: 3,
                lottery_id: 0,
                create_time: null,
                end_time: null,
                show: false,
                luckerArr: [],
                sign: ''
            }
        },
        watch: {
            'userStatus': function (val, oldVal) {
                // 如果是登录状态
                console.log("stat" + val + "," + oldVal)
                user.setCookie('login_status', val)
                switch (val) {
                    case status.__init:

                        break;
                    case status.__ing:
                        //2）创建时间+抽奖时间
                        // this.downtime = dateformat(new Date(new Date(this.create_time).getTime()+parseInt(this.luck_time)*10000),"yyyy-mm-dd HH:MM:ss")
                        // this.downtime = dateformat(new Date(new Date(this.create_time) - 8 * 60 * 60 * 1000 + parseInt(this.luck_time) * 10 * 1000), "yyyy-mm-dd HH:MM:ss")
                        this.downtime = dateformat(new Date(new Date(this.end_time) - 8 * 60 * 60 * 1000), "yyyy-mm-dd HH:MM:ss")

                        break;
                    case status.__joined:
                        this.point = '第二次准备'
                        let sign = localStorage.getItem('sign')
                        this.sign = sign
                        var _ = this
                        if (sign == 'sign') {
                            _.point = '第二次加入'
                            user.socket.on('notify', function (data) {
                                // 置0,将状态改为初始状态
                                localStorage.removeItem('cookie_time')
                                localStorage.removeItem('lottery_id')
                                localStorage.removeItem('sign')
                                var info = ''
                                if (data.some(function (el) {
                                    return el.openid == user.userinfo.openid
                                })) {
                                    info = "恭喜您中奖了，请联系管理员领奖"
                                } else {
                                    data.forEach(function (el) {
                                        info += el.nick + '|'
                                    })
                                    info = info.slice(0, -1)
                                }
                                _.$vux.alert.show({
                                    title: '提示',
                                    content: info
                                })
                                _.userStatus = status.__init
                                // 收到通知后 取消订阅
                                // user.socket.emit('cancelSubscribe',{openid:user.userinfo.openid})
                            })
                        } else {
                            _.point = '第一次预备'
                            _.$axios.post("/lottery/join", {
                                lottery_id: _.lottery_id,
                                openid: user.userinfo.openid,
                                nick: user.userinfo.nick,
                                head: user.userinfo.head,
                                trade_no: _.query.trade_no
                            }).then(function (ret) {
                                // 订阅中奖名单
                                _.point = '第一次加入'
                                localStorage.setItem('sign', 'sign')
                                user.socket.emit('subscribe', {
                                    mch_id: user.userinfo.mch_id,
                                    openid: user.userinfo.openid,
                                    nick: user.userinfo.nick,
                                    tag: _.lottery_id
                                })
                                // 监听通知
                                user.socket.on('notify', function (data) {
                                    // 置0,将状态改为初始状态
                                    localStorage.removeItem('cookie_time')
                                    localStorage.removeItem('lottery_id')
                                    localStorage.removeItem('sign')
                                    var info = ''
                                    if (data.some(function (el) {
                                        return el.openid == user.userinfo.openid
                                    })) {
                                        info = "恭喜您中奖了，请联系管理员领奖"
                                    } else {
                                        data.forEach(function (el) {
                                            info += el.nick + '|'
                                        })
                                        info = info.slice(0, -1)
                                    }
                                    _.$vux.alert.show({
                                        title: '提示',
                                        content: info
                                    })
                                    _.userStatus = status.__init
                                    // 收到通知后 取消订阅
                                    // user.socket.emit('cancelSubscribe',{openid:user.userinfo.openid})
                                })

                            })
                        }
                        break;
                    case status.__ending:
                        // var _ = this
                        // setTimeout(function(){
                        //     _.end()
                        // },20000)
                        break;
                    case status.__end:
                        break;
                    default:
                }
            },
            'user.status': function (val, oldVal) {
                alert('付款改变')
            }
        },
        mounted() {
            this.query = this.$route.query
            // this.trade_no = this.query.replace('wx=','')
            user.status = 0
            user.userinfo.mch_id = 1
            if (!localStorage.getItem('cookie_time')) {
                // 初始化进来的界面
                this.userStatus = status.__init
                user.userinfo.mch_name = '1912'
                this.downtime = ''
                this.lottery_id = 0
            } else {
                this.downtime = localStorage.getItem('cookie_time')

                let d = this.downtime.split(" ")[0]
                let t = this.downtime.split(" ")[1]
                let cookieTime = new Date(d.split('-')[0], d.split('-')[1] - 1, d.split('-')[2], t.split(':')[0], t.split(':')[1], t.split(':')[2]).getTime()

                let nowTime = new Date().getTime()
                console.log(cookieTime > nowTime)
                console.log(cookieTime)
                console.log(nowTime)
                if (cookieTime > nowTime) {
                    // cookie未来时间大于当前时间
                    this.userStatus = status.__joined
                    this.downtime = localStorage.getItem('cookie_time')
                    this.lottery_id = localStorage.getItem('lottery_id')
                } else {
                    this.userStatus = status.__init
                    user.userinfo.mch_id = 1
                    user.userinfo.mch_name = '1912'
                    this.downtime = ''
                    this.lottery_id = 0
                    localStorage.removeItem('cookie_time')
                    localStorage.removeItem('lottery_id')
                }
            }
        },
        methods: {
            clear() {
                localStorage.removeItem("cookie_time")
                localStorage.removeItem("lottery_id")
                localStorage.removeItem("sign")
            },
            putin() {
                this.$router.push({ path: '/lottery/pay' })
            },
            refresh() {
                this.clear()
                var _ = this
                this.$axios.get("/lottery/getOne?mch_id=" + user.userinfo.mch_id)
                    .then(function (ret) {
                        if (ret.data.info === 0) {
                            //    alert('请等待管理员开启')
                        } else {
                            //1）刷新获取创建时间                        
                            _.luck_num = ret.data.luck_num
                            _.prize = ret.data.prize
                            _.price = ret.data.price
                            _.luck_time = ret.data.luck_time
                            _.lottery_id = ret.data.lottery_id
                            _.create_time = ret.data.create_time
                            _.end_time = ret.data.end_time

                            // 提前10秒结束
                            if ((new Date(_.end_time) - 8 * 60 * 60 * 1000 - 10 * 1000) > new Date()) {
                                _.userStatus = status.__ing
                            }
                            // alert(this.create_time)

                        }
                    })
                    .catch(function (error) {
                        // console.log('aa')
                    })
            },
            join() {
                localStorage.setItem('cookie_time', this.downtime)
                localStorage.setItem('lottery_id', this.lottery_id)
                this.$router.push({ path: '/lottery/pay' })
                // this.$router.go(0)
            },
            scan() {
                var _ = this
                wx.scanQRCode({
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success: function (res) {
                        var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                        var url = ""
                        // 必须以这个路由路径开头－才算扫这个码
                        // 1、扫桌面商户
                        if (result.indexOf('/merchant/getById') == 0) {
                            _.$axios.get(result)
                                .then(function (ret) {
                                    user.userinfo.mch_id = result.data
                                    user.userinfo.mch_name = ret.data.mch_name
                                    actor.stat = status.__login
                                })
                        }
                        // 2、扫员工授权
                        if (result.indexOf('/user/grantTo') == 0) {
                            url = result + "&openid=" + user.userinfo.openid
                            _.$axios.get(url)
                                .then(function (ret) {
                                    if (ret.data.info == 'success') {
                                        alert("授权成功")
                                    }
                                })
                                .catch(function (error) {
                                    alert("error")
                                })
                        }
                        // 3、扫老板授权
                        if (result.indexOf('/user/grantBoss') == 0) {
                            url = result + "&openid=" + user.userinfo.openid
                            _.$axios.get(url)
                                .then(function (ret) {
                                    if (ret.data.info == 'success') {
                                        alert("授权成功")
                                    }
                                })
                                .catch(function (error) {
                                    alert("error")
                                })
                        }

                    }
                });

                console.log("__login")
            },
            ending() {
                actor.stat = status.__ending
                console.log("__ending")
            },
            end() {
                actor.stat = status.__end
                console.log("__end")
            }
        }
    }
</script>

<style lang="less" scoped>
    @import '~vux/src/styles/close';

    .dialog-demo {
    .weui-dialog{
        border-radius: 8px;
        padding-bottom: 8px;
    }
    .dialog-title {
        line-height: 30px;
        color: #666;
    }
    .img-box {
        height: 350px;
        overflow: hidden;
    }
    .vux-close {
        margin-top: 8px;
        margin-bottom: 8px;
    }
    }

    /*div {
        height: 100%
    }*/

    .box {
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    .item1 {
        flex:1
    }

    .item2 {
        flex:2
    }

</style>